package session.stateless.CRM;

import entity.CRM.Customer;
import entity.CRM.Representative;
import entity.CRM.SaleInquiry;
import entity.CRM.SaleLead;
import entity.CRM.SaleLead.CustomerType;
import entity.CRM.SaleQuotation;
import entity.Employee;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.ejb.Remove;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class SaleLeadBean implements SaleLeadBeanLocal {
    @PersistenceContext(unitName = "M10-IS3102-ejbPU")
    EntityManager em;
    
    public SaleLeadBean(){}
    
    public Representative createRepresentative(String name, String email, String contactNumber)
    {
        Representative rep = new Representative();
        rep.setName(name);
        rep.setEmail(email);
        rep.setContactNumber(contactNumber);
        em.persist(rep);
//        SaleLead saleLead = em.find(SaleLead.class, reg_num);
//        if (saleLead != null)
//        {
//            rep.setSaleLead(saleLead);
//            em.persist(rep);
//            saleLead.getRepresentatives().add(rep);
//        }
//        em.flush();
        return rep;
    }
    
    public void updateRepresentative(String email, String contactNumber) {
        Representative representative=em.find(Representative.class, email);
        if (representative!=null)
        {
            representative.setEmail(email);
            representative.setContactNumber(contactNumber);
            em.flush();
            
        }
    }
    public void deleteRepresentative(String email) {
        Representative representative = em.find(Representative.class, email);
        em.remove(representative);               
        em.flush();
    }
    
    public void createSaleLead(String name, String reg_num, String address, CustomerType customerType, List<Representative> representatives, Long executiveId) {
        SaleLead saleLead = new SaleLead();
        saleLead.setSaleLeadName(name);
        saleLead.setRegistrationNumber(reg_num);
        saleLead.setRepresentatives(representatives);
        saleLead.setSaleLeadAddress(address);
        saleLead.setCustomerType(customerType);
        saleLead.setIsActive(true);
        
        Employee executive = em.find(Employee.class, executiveId);
        saleLead.setCustomerExecutive(executive);
        
        
        em.persist(saleLead); 
        em.flush();
        
        for (Representative temp: saleLead.getRepresentatives())
            temp.setSaleLead(saleLead);
        em.flush();
    }

    public void updateSaleLead(String reg_num, String saleLeadName,String saleLeadAddress, CustomerType customerType, List<Representative> representatives) 
    {
        SaleLead saleLead = em.find(SaleLead.class, reg_num);       
        if (saleLead !=null)
        {
            saleLead.setSaleLeadName(saleLeadName);
            saleLead.setSaleLeadAddress(saleLeadAddress);
            saleLead.setCustomerType(customerType);
            
            List<Representative> temps = saleLead.getRepresentatives();
            saleLead.setRepresentatives(null);
            Representative rep = new Representative();
            
            for (int i = 0; i < temps.size(); i++)
            {
                rep = temps.get(i);
                deleteRepresentative(rep.getEmail());
            }
            
            temps = new ArrayList<Representative>();
            for (int i = 0; i < representatives.size(); i++) {
                temps.add(createRepresentative(representatives.get(i).getName(), representatives.get(i).getEmail(), representatives.get(i).getContactNumber()));
            }            
            saleLead.setRepresentatives(temps);
        }
        em.flush();
    }
    
    public void deleteSaleLead(String reg_num) {
        SaleLead saleLead = em.find(SaleLead.class, reg_num);
        if (saleLead!=null)
        {
            List<Representative> temp_rep =saleLead.getRepresentatives();
            for (Representative representative:temp_rep)
            {
                representative.setSaleLead(null);
                em.remove(representative);
            }
            temp_rep.clear();
            
            
            List<SaleQuotation> temp_SQ = saleLead.getSaleQuotations();
            for (SaleQuotation saleQuotation:temp_SQ)
            {
                saleQuotation.setSaleLead(null);
                em.remove(saleQuotation);
            }
            temp_SQ.clear();
            
            List<SaleInquiry> temp_SI = saleLead.getSaleInquiries();
            for (SaleInquiry saleInquiry:temp_SI)
            {
                  saleInquiry.setSaleLead(null);
                  em.remove(saleInquiry);
            }
            temp_SI.clear();
            
            saleLead.setCustomerExecutive(null);
            em.remove(saleLead);
            em.flush();
            //em.merge(saleLead);
        }
    }
    
    public List<SaleLead> getSalesLead(Long id) {
        Employee executive = em.find(Employee.class, id);
        Query q = em.createQuery("SELECT c FROM SaleLead c WHERE c.customerExecutive =:executive AND c.isActive=:true");
        q.setParameter("executive", executive);
        q.setParameter("true", true);
        List<SaleLead> temp_SaleLead =q.getResultList();
        
        Query p=em.createQuery("SELECT p FROM Customer p WHERE p.customerExecutive =:executive AND p.isActive=:true");
        p.setParameter("executive", executive);
        p.setParameter("true", true);
        List<SaleLead> temp_Customer=p.getResultList();
        
        for (Object o:temp_Customer)
        {
            SaleLead temp=(SaleLead) o;
            temp_SaleLead.remove(temp);            
        }
        
            return temp_SaleLead;        
    }
    
    public List<SaleLead> getAllSalesLead()
    {
        Query q = em.createQuery("SELECT c FROM SaleLead c");
        return q.getResultList();
    }
    
    @Remove
    public void remove() {
       System.out.println("SaleLeadBean:remove()");               
    }

    public SaleLead find(String registrationNumber) {
        if  (em.find(SaleLead.class, registrationNumber)!=null)
            return em.find(SaleLead.class,registrationNumber);
        else 
            return em.find(Customer.class,registrationNumber);
    }
    
    public boolean checkNRIC(String NRIC) {
        String[] temp_array = {"S", "F", "T", "G"};
        ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(temp_array));
        String prefix = NRIC.trim().substring(0,1);
        if (!arrayList.contains(prefix))
        {
            return false;
        }
        else 
        {
            if (NRIC.length() != 9)
                return false;
            else
            {
                try
                {
                    Integer t = (Integer.parseInt(NRIC.substring(1,8)));
                }
                catch (NumberFormatException nfe)
                {
                    return false;
                }
                return true;
            }
        }
    }
    public boolean checkEmail(String email){
        if (!email.contains("@"))
        {
            return false;
        }
        else
        {
            int index = email.indexOf("@");
            String substring = email.substring(index+1);
            if ((substring.contains("@")) || (!substring.contains(".")))
            {
                return false;
            }
            else
                return true;
        }
    }
    public boolean checkContactNumber (String contactNumber){
        Integer temp;
        int count = 1;
        try 
        {
            temp = Integer.parseInt(contactNumber);
        }
        catch (NumberFormatException nfe)
        {
            return false;
        }
        
        int div = 10;
        while (temp / div > 0)
        {
            div *=10;
            count+=1;
        }
        if ((count > 15) || (count < 8))
        {
            return false;
        }
        else
            return true;
    }

    public SaleLead findByName(String saleLeadName) 
    {
        Query q=em.createQuery("SELECT c FROM SaleLead c WHERE c.saleLeadName=:saleLeadName");
        q.setParameter("saleLeadName", saleLeadName);
        
        return (SaleLead) q.getSingleResult();
    }

}
